package com.webserver_v3.core;

import com.webserver_v3.controller.UserController;
import com.webserver_v3.http.HttpServletRequest;
import com.webserver_v3.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;

public class DispatcherServlet {
    private static DispatcherServlet instance = new DispatcherServlet();

    private static File rootDir;
    private static File staticDir;

    private DispatcherServlet(){}
    public static DispatcherServlet getInstance(){
        return instance;
    }
    static {
        try {
            //定位类加载路径
            rootDir = new File(
                    ClientHandler.class.getClassLoader()
                            .getResource(".").toURI()
            );

            //定位static目录
            staticDir = new File(rootDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public void service(HttpServletResponse response, HttpServletRequest request){
        String path = request.getRequestURI();
        if ("/regUser".equals(path)){
            UserController controller = new UserController();
            controller.reg(request,response);
        }else {
            File file = new File(staticDir,path);
            if  (file.isFile()){
                response.setContentFile(file);

            }else {
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file = new File(staticDir,"root/404.html");
                response.setContentFile(file);

            }
        }
    }
}
